package com.base.security.realm;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;

/**
 * 登录身份认证，同时提供用户的身份信息。
 * @author Shisan
 *
 */
public class UserRealm extends AuthorizingRealm {
	/* (non-Javadoc)
	 * @see org.apache.shiro.realm.AuthorizingRealm#doGetAuthorizationInfo(org.apache.shiro.subject.PrincipalCollection)
	 * 该方法用于权限认证
	 * //角色与权限。角色和权限是动态获取的，这里将使用编程方式进行验证。
				//权限有：a:全部，r:查询，w:增删改，c:审核
				//角色=岗位
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principal) {
		String currentUsername = (String)super.getAvailablePrincipal(principal);
		if(StringUtils.isBlank(currentUsername)){
			return null;
		}
		Session session = SecurityUtils.getSubject().getSession();
		//添加角色和权限对象
		SimpleAuthorizationInfo simpleAuthor = new SimpleAuthorizationInfo();
		return simpleAuthor;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.apache.shiro.realm.AuthenticatingRealm#doGetAuthenticationInfo(org.
	 * apache.shiro.authc.AuthenticationToken) 登录身份认证
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authentic) throws AuthenticationException {
		UsernamePasswordToken upt = (UsernamePasswordToken) authentic;
		String userName = upt.getUsername();
		if (StringUtils.isBlank(userName)) {
			throw new UnknownAccountException("用户名不能为空");
		}
		Subject subject = SecurityUtils.getSubject();
		Session session = subject.getSession();
		//password不是加密后的密码
		SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(userName, "password",
				this.getName());
		return simpleAuthenticationInfo;
	}

}
